<?php
// +----------------------------------------------------------------------
// | SwiftPHP [ JUST DO ONE THING WELL ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2017  http://swiftphp.zhongwenyu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: zhongwenyu <zhongwenyu1987@163.com> <http://www.zhongwenyu.com>
// +----------------------------------------------------------------------
// | Times: 2017/2/23 16:21
// +----------------------------------------------------------------------
namespace swift;

class Curl{

    // 初始化
    protected static $init = null;

    protected static function init(){
        if(is_null(self::$init)){
            self::$init = curl_init();
        }
        return self::$init;
    }

    /**
     * get请求
     * @param string $url
     * @param array $args
     * @param int $timeout
     * @return bool|mixed
     */
    public static function get($url = '' , $data = [] , $timeout = 3){
        if(empty($url)){
            return false;
        }

        if(!empty($data)){
            strpos($url , '?') !== false && $url .= '?';
            $url .= http_build_query($data);
        }

        $option = [
            CURLOPT_URL             =>  $url,
            CURLOPT_HEADER          =>  false,  // 不返回头文件信息
            CURLOPT_RETURNTRANSFER  =>  true,  // 将curl_exec()获取的信息以文件流的形式返回，而不是直接输出
            CURLOPT_TIMEOUT         =>  intval($timeout)    // 设置cURL允许执行的最长秒数
        ];

        self::setopt($option);

        $result = self::execute();

        self::close();

        return $result;
    }

    /**
     * post请求
     * @param string $url
     * @param array $args
     * @param int $timeout
     * @return bool|mixed
     */
    public static function post($url = '' , $data = [] , $timeout = 30){
        if(empty($url)){
            return false;
        }

        $option = [
            CURLOPT_URL             =>  $url,
            CURLOPT_HEADER          =>  false,  // 不返回头文件信息
            CURLOPT_RETURNTRANSFER  =>  true,  // 将curl_exec()获取的信息以文件流的形式返回，而不是直接输出
            CURLOPT_TIMEOUT         =>  intval($timeout),    // 设置cURL允许执行的最长秒数
            CURLOPT_POSTFIELDS      =>  http_build_query($data)    // 注意，此处不使用http_build_query，直接使用$data也是可以的，但效率很差
        ];

        self::setopt($option);

        $result = self::execute();

        self::close();

        return $result;
    }

    protected static function setopt($option , $value = null){
        if(is_array($option)){
            foreach($option as $key => $val){
                self::setopt($key , $val);
            }
        }else{
            curl_setopt(self::init() , $option , $value);
        }
    }

    protected static function execute(){
        return curl_exec(self::init());
    }

    protected static function close(){
        self::$init = null;
        curl_close(self::$init);
    }
}
